var express = require('express');
var router = express.Router();
var captcha = require('svg-captcha')
var jwt = require('jsonwebtoken');
var { usersModel, roleModel, IOAModel, room_typeModel, reservationModel, customModel ,depositModel,room_numberModel } = require("../../model/model")

/* GET home page. */

//寄存列表
router.get('/deposit',async(req,res)=>{
  let { pageSize, currentPage,  status,
    deposit_date,
    Extraction_time,
    registrant,
    deposit_article,} = req.query


    let deposit = []

  if(status){
    deposit = await depositModel.find({status:status }).populate("custom_id")
  }else if(deposit_date && Extraction_time){
    deposit = await depositModel.find({ deposit_date: { $gte: deposit_date, $lte:Extraction_time } }).populate("custom_id")
  }else if(registrant){
    deposit = await depositModel.find({ registrant: registrant }).populate("custom_id")
  }else if(deposit_article){
    deposit = await depositModel.find({ deposit_article:deposit_article }).populate("custom_id")
  }else{
    deposit = await depositModel.find().populate("custom_id")
  }

  let total = deposit.length
  let pagelist = deposit.slice((currentPage - 1) * pageSize, currentPage * pageSize)

  res.send({
    code:200,
    total,
    pagelist
  })
})

//添加寄存
router.post('/deposit_add', async (req, res) => {
  await depositModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})


//提取寄存
router.put('/deposit_edit', async (req, res) => {
  let body = req.body
  let _id = body._id
  await depositModel.updateOne({ _id }, body)

  res.send({
    code: 200,
    msg: '修改成功'
  })
})



//客户列表
router.get('/custom', async (req, res) => {
  let { pageSize, currentPage, VIP_Level,
    gender,
    name,
    tell,
    document_number } = req.query
  let regad_name = new RegExp(name)

  let custom =[]

  if(VIP_Level){
    custom = await customModel.find({ $and:[{VIP_Level:VIP_Level},{gender:gender},{name:regad_name}] })
  }else if(VIP_Level){
    custom = await customModel.find({VIP_Level:VIP_Level})
  }else if(gender){
    custom = await customModel.find({ gender: gender })
  }else if(name){
    custom = await customModel.find({ name: regad_name })
  }else if(tell){
    custom = await customModel.find({ tell: tell }).populate('VIP_id')
  }else if(document_number){
    custom = await customModel.find({ document_number: document_number })
  }else{
    custom = await customModel.find()
  }

  let total = custom.length
  let pagelist = custom.slice((currentPage - 1) * pageSize, currentPage * pageSize)

  res.send({
    pagelist,
    total
  })
})

//添加客户
router.post('/custom_add', async (req, res) => {
  await customModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

//修改客户
router.put('/custom_edit', async (req, res) => {
  let body = req.body
  let _id = body._id
  await customModel.updateOne({ _id }, body)

  res.send({
    code: 200,
    msg: '修改成功'
  })
})

//删除客户
router.delete('/custom_delete', async (req, res) => {
  let { _id } = req.query
  await customModel.deleteOne({ _id })

  res.send({
    code: 200,
    msg: '删除成功'
  })
})


//预约列表
router.get('/reservation', async (req, res) => {
  let { pageSize, currentPage} = req.query
  let reservation = await reservationModel.find().populate("room_id").populate('custom_id').populate('house_id')
  let total = reservation.length
  let pagelist = reservation.slice((currentPage - 1) * pageSize, currentPage * pageSize)
  res.send({
    pagelist,
    total
  })
})

//添加预约
router.post('/reservation_add', async (req, res) => {
  await reservationModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})



//获取房间类型
router.get('/room_type', async (req, res) => {
  let room_type = await room_typeModel.find()
  res.send({
    room_type
  })
})


//添加房间类型
router.post('/room_type_add', async (req, res) => {
  await room_typeModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

//登录
router.get('/login', async (req, res) => {
  let { username, password } = req.query

  const obj = await usersModel.find({ $and: [{ username }, { password }] })

  if (obj) {
    let token = "Bearer " + jwt.sign({ username: obj[0].username }, 'xl', { expiresIn: "1h" })
    res.send({ code: 200, msg: '登陆成功', token, obj })
  }
})



//获取验证码
router.get('/get_captch', (req, res) => {
  let cap = captcha.create()

  res.type('svg')
  res.status(200).send({
    data: cap.data,
    text: cap.text
  })
})


//登录与注册
router.post('/login', async (req, res) => {
  let { phone } = req.body
  let user = await usersModel.findOne({ phone })
  if (user) {
    //用户存在进行token返回
    const accessToken = jwt.sign({ userId: user._id }, key, { expiresIn: '1h' })
    const refreshToken = jwt.sign({ userId: user._id }, key, { expiresIn: '0.5d' })

    res.send({
      code: 200,
      msg: '登录成功',
      data: user,
      accessToken,
      refreshToken
    })
  } else {

    //用户不存在进行注册
    usersModel.create(req.body)

    res.send({
      code: 200,
      msg: '注册成功',
    })
  }
})

//获取用户列表
router.get('/users_list', async (req, res) => {
  let users_list = await usersModel.find();
  res.send({
    users_list
  })
});

//获取角色列表
router.get('/role_list', async (req, res) => {
  let role_list = await roleModel.find();
  res.send({
    role_list
  })
});


//获取IOA权限列表
router.get('/IOA_list/:rid', async (req, res) => {
  let rid = req.params.rid
  let [IOAid] = await roleModel.find({ _id: rid })

  let IOAlist = await IOAModel.find().lean()

  let IOA = []
  IOAid.Iid.forEach(id => {
    IOAlist.forEach(item => {
      if (String(id) === String(item._id)) {
        IOA.push(item)
      }
    })
  })

  let cateObj = {}
  IOA.forEach(item => {
    cateObj[item._id] = item
  })

  let data = []
  IOA.forEach((item) => {
    if (!item["Iid"]) {
      data.push(item)
    } else {
      if (cateObj[item["Iid"]] && !cateObj[item["Iid"]]["children"]) {
        cateObj[item["Iid"]]["children"] = []

      }
      if (cateObj[item["Iid"]]) {
        cateObj[item["Iid"]]["children"].push(item)
      }
    }
  })
  res.send({
    code: 200,
    data
  })
})



module.exports = router;
